<template>
  <div style="float: left;margin-top: 5px">
    <el-form ref="searchRef" :model="searchFormData">
      <el-form-item label="关键词">
        <el-input type="text" v-model="searchFormData.containerName"></el-input>
      </el-form-item>
    </el-form>
  </div>
  <div style="height: 40px;margin-top: 5px;float: left;margin-left: 20px;">
    <el-button @click="searchClick">查询</el-button>
    <el-button @click="resetSearchClick">重置</el-button>
    <el-button @click="addClick">新增</el-button>
    <el-button @click="deployDockerContainer">部署</el-button>
    <el-button @click="startDockerContainer">开启</el-button>
    <el-button @click="stopDockerContainer">停止</el-button>
    <el-button  @click="clearExceptionContains">清洗异常容器</el-button>
  </div>
  <div style="clear: both"></div>
  <div style="height: calc(100% - 60px);">
    <Table :show-page="true" ref="tableRef" :show-line-number="true"
           :showCheckBox="false" :url="tableUrl" :columns="columns"  >
      <template v-slot:handle="slotProps">
        <el-button v-if="slotProps.rowData.deployState == 0 " @click.stop="editTableData(slotProps.rowData,slotProps.rowIndex)">编辑</el-button>
<!--
        <el-button v-if="slotProps.rowData.deployState == 0 " @click.stop="editTableData(slotProps.rowData,slotProps.rowIndex)">参数管理</el-button>
-->
        <el-button @click.stop="deleteTableRowData(slotProps.rowData,slotProps.rowIndex)">删除</el-button>
        <el-button v-if="slotProps.rowData.deployState == 1" @click.stop="backupDockerContainer(slotProps.rowData,slotProps.rowIndex)">备份</el-button>
        <el-button v-if="slotProps.rowData.deployState == 1" @click.stop="restoreDockerContainer(slotProps.rowData,slotProps.rowIndex)">恢复</el-button>
      </template>
    </Table>
  </div>
  <DialogForm width="500px" ref="editFormRef" :form="settingForm" title="编辑" @validateSuccess="validateSuccess">
  </DialogForm>

  <DialogForm width="500px" ref="backupEditFormRef" :form="backupSettingForm" title="编辑" @validateSuccess="backupValidateSuccess">
  </DialogForm>
  <DialogForm width="500px" ref="containerFormRef" :form="containerForm" title="编辑" @validateSuccess="clearValidateSuccess">
  </DialogForm>
  <el-dialog title="备份列表" v-model="dialogBackupVisible" :close-on-click-modal="false" >
    <Table :show-page="true" ref="backupTableRef" :show-line-number="true"
           :showCheckBox="false"  :columns="backupColumns"  >
    </Table>
    <div style="text-align: right" >
      <el-button type="primary"  @click="submitRestoreContainer">提交</el-button>
    </div>
  </el-dialog>
</template>

<script setup>

import Table from "@/components/plugs/table/Table.vue";
import DialogForm from "@/components/plugs/form/DialogForm.vue";
import {inject, reactive, ref, toRaw} from "vue";
import {FormItemType} from "@/components/plugs/form/DialogFormInterface.js";
import {AXIOS_NAME} from "@/constant/constant.js";
import {ElMessage, ElMessageBox} from "element-plus";
import {deleteRow, HandleEnum} from "@/utils/utils.ts";
import {CheckModel} from "@/components/plugs/table/TableInterface.js";

const backupTableRef = ref(null);
const backupEditFormRef = ref(null);
const tableRef = ref(null);
const $axios = inject(AXIOS_NAME);
const searchRef = ref(null);
const editFormRef = ref(null);
const dialogBackupVisible = ref(false);
const backupList = reactive([]);
const tableUrl = ref("/deploy/getDeployPage");
const containerFormRef = ref(null);

const searchFormData = reactive({
  'containerName': ''
});

let containerFormItems = [];
containerFormItems.push({type: FormItemType.CUSTOMIZE_SELECT,label: '清洗容器',name: 'containerIds',
  url: '/deploy/getDeployedContainerList',textFiled:'containerName',valueField: "id",isMultiple:true});
let containerForm = reactive({
  splitCol: 1,
  gutter: 20,
  labelWidth: 115,
  items: containerFormItems,
  rules: {},
});

const backupColumns = [
  {field: "name", "desc": "名称"},
];
const columns = [
  {field: "imageName", "desc": "镜像名称"},
  {field: "containerName", "desc": "容器名称"},
  {field: "containerType", "desc": "容器类型", dicType: "container_type"},
  {field: "processName", "desc": "进程名称"},
  {field: "runModel", "desc": "运行模式"},
  {
    field: "resourceInfo", "desc": "分配资源", colFormatVal: function (rowData, dicData, colIndex, rowIndex) {
      let str = "";
      if (rowData.cpu != 0) {
        str += "cpu：" + rowData.cpu + " ";
      }
      if (rowData.memory != 0) {
        str += "内存：" + rowData.memory + "M ";
      }
      if (rowData.disk != 0) {
        str += "硬盘：" + rowData.disk + "M ";
      }
      return str;
    }
  },
  {field: "deployState", "desc": "部署状态", dicType: "deploy_state"},
  {field: "runState", "desc": "运行状态", dicType: "run_state"},
  {field: "hasEnter", "desc": "是否可进入", dicType: "has_enter"},
  {field: "hasEnableBackup", "desc": "是否备份",dicType: "start_using"},
  {field: "scheduledCorn", "desc": "调度规则"},
  {field: "showTime", "desc": "创建时间", width: 200},
  {field: "handle", "desc": "操作", isSlot: true, width: 250}
];

let items = [];
items.push({type: FormItemType.INPUT_HIDDEN, label: 'id', name: 'id'});
items.push({type: FormItemType.INPUT_TEXT, label: '容器名称', name: 'containerName'});
items.push({
  type: FormItemType.CUSTOMIZE_SELECT, label: '容器类型', name: 'containerType',
  url: '/dictionary/getDicDataByGroupId?groupId=container_type', textFiled: 'text', valueField: "val", defaultValue: '1'
});
items.push({type: FormItemType.INPUT_HIDDEN, label: '部署状态', name: 'deployState', defaultValue: '0'});
items.push({type: FormItemType.INPUT_HIDDEN, label: '运行状态', name: 'runState', defaultValue: '0'});
items.push({type: FormItemType.INPUT_HIDDEN, label: '是否可进入', name: 'hasEnter', defaultValue: '0'});
let settingForm = reactive({
  splitCol: 1,
  gutter: 20,
  labelWidth: 115,
  items: items,
  rules: {},
});

let backupItems = [];
backupItems.push({type: FormItemType.INPUT_HIDDEN, label: 'id', name: 'id'});
backupItems.push({type: FormItemType.DIC_SELECT, label: '是否开启', name: 'hasEnableBackup',dicType:'start_using'});
backupItems.push({type: FormItemType.INPUT_TEXT, label: '调度规则', name: 'scheduledCorn'});
let backupSettingForm = reactive({
  splitCol: 1,
  gutter: 20,
  labelWidth: 115,
  items: backupItems,
  rules: {},
});
const searchClick = () => {
  tableRef.value.reload(toRaw(searchFormData));
}

const resetSearchClick = () => {
  searchFormData.containerName = '';
}

const addClick = () => {
  editFormRef.value.show();
}

const editTableData = (rowData, rowIndex) => {
  editFormRef.value.show();
  editFormRef.value.setData(rowData);
}

const deleteTableRowData = (rowData, rowIndex) => {
  deleteRow('/deploy/delete', rowData, function (state, data) {
    if (state == HandleEnum.SUCCESS) {
      tableRef.value.reload();
    }
  });
}

const validateSuccess = (data) => {
  $axios.post('/deploy/addOrUpdate', data).then(response => {
    const data = response.data;
    if (data.code == 1) {
      tableRef.value.reload();
      editFormRef.value.close();
      ElMessage.info("操作成功！");
      return;
    }
    ElMessage.error(data.msg);
  }, error => {

  });
}

const deployDockerContainer = () => {
  const checkData = tableRef.value.getCheckedData();
  if(checkData.length <= 0){
    ElMessage.error("请选择一条数据!")
    return;
  }
  ElMessageBox.confirm(
      '是否部署容器?','提示',{
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
  ).then(() => {
    $axios.post("/deploy/deploy",checkData[0]).then(response => {
      ElMessage.info(response.data.msg);
      if(response.data.code == 1){
        tableRef.value.reload();
      }
    });
  });

}

const backupDockerContainer = (rowData,rowIndex) =>{
  backupEditFormRef.value.show();
  backupEditFormRef.value.setData(rowData);
}

const submitRestoreContainer = () =>{
  const rowDataArr = backupTableRef.value.getCheckedData();
  if(rowDataArr.length <= 0 ){
    ElMessage.error("请选择一条数据!");
    return;
  }
  $axios.post('/deploy/restoreContainerData',rowDataArr[0]).then(response => {
    const data = response.data;
    if(data.code == 1){
      dialogBackupVisible.value = false;
      ElMessage.info("操作成功!");
      return;
    }
    ElMessage.error("操作失败!");
  });
}

const restoreDockerContainer = (rowData,rowIndex) =>{
  ElMessageBox.confirm(
      '是否清洗容器?','提示',{
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
  ).then(() => {
    dialogBackupVisible.value = true;
    $axios.post("/deploy/getBackupList",rowData).then(response => {
      const data = response.data;
      backupList.clear();
      for(const item of data.data){
        backupList.push({"name":item,"id":rowData.id});
      }
      backupTableRef.value.setData(toRaw(backupList));
    });
  });
};

const startDockerContainer = () => {
  const checkData = tableRef.value.getCheckedData();
  if(checkData.length <= 0){
    ElMessage.error("请选择一条数据!")
    return;
  }
  ElMessageBox.confirm(
      '是否启动容器?','提示',{
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
  ).then(() => {
    $axios.post("/deploy/start",checkData[0]).then(response => {
      ElMessage.info(response.data.msg);
      if(response.data.code == 1){
        tableRef.value.reload();
      }
    });
  });
}

const stopDockerContainer = () => {
  const checkData = tableRef.value.getCheckedData();
  if(checkData.length <= 0){
    ElMessage.error("请选择一条数据!")
    return;
  }
  ElMessageBox.confirm(
      '是否停止容器?','提示',{
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
  ).then(() => {
    $axios.post("/deploy/stop",checkData[0]).then(response => {
      ElMessage.info(response.data.msg);
      if(response.data.code == 1){
        tableRef.value.reload();
      }
    });
  });

}

const backupValidateSuccess = (data) =>{
  $axios.post("/deploy/updateContainerBackupCorn",data).then(response => {
    const data = response.data;
    if(data.code != 1){
      ElMessage.error(data.msg);
      return;
    }
    ElMessage.info(data.msg);
    backupEditFormRef.value.close();
    tableRef.value.reload();
  });
}

const clearExceptionContains = () => {
  containerFormRef.value.show();
}
const clearValidateSuccess = (data) => {
  debugger;
  if(data.containerIds == undefined || data.containerIds == ''){
    ElMessage.error("请选择容器数据!");
    return;
  }
  data.containerIds = JSON.stringify(data.containerIds);
  $axios.post("/deploy/clearExceptionContainers",data).then(response => {
    const data = response.data;
    ElMessage.info(data.msg);
  });
}
</script>

<style scoped>
.docker-backup-list-item{
  height: 35px;
  line-height: 35px;
  font-size: 16px;
}
</style>